package com.shengchang.hu.supervision.UI;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Parcelable;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.shengchang.hu.supervision.Adapter.BloodBagAdapter;
import com.shengchang.hu.supervision.Adapter.InBouGridAdapter;
import com.shengchang.hu.supervision.Api.PrintHelper;
import com.shengchang.hu.supervision.Application.App;
import com.shengchang.hu.supervision.R;
import com.shengchang.hu.supervision.ToolBar.InBoundBar;
import com.shengchang.hu.supervision.Utils.BarcodeUtil;
import com.shengchang.hu.supervision.Utils.Contants;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import NFC.NdefMessageParser;
import NFC.ParsedNdefRecord;
import Tcp.Tcp_Client;
import hardware.print.printer;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class BloodBagInBoundActivity extends BaseActivity implements View.OnClickListener {


    InBoundBar inboundbar;
    TextView Cweghit;
    EditText weightEdit;
    GridView grid;
    TextView keshi;
    Button endShoujiBtn;
    EditText jiaoyanEdit;
    RelativeLayout jiaoyan;
    Button chongfuBtn;
    private String mTitleStr = "广州省人民医院医院医废 ";
    /*读取IC卡功能*/
    String  m_Broadcastname = "com.barcode.sendBroadcast";
   MyCodeReceiver receiver = new MyCodeReceiver();

    private static final DateFormat TIME_FORMAT = SimpleDateFormat
            .getDateTimeInstance();
    private NfcAdapter mAdapter;
    private PendingIntent mPendingIntent;
    private NdefMessage mNdefPushMessage;
    private android.app.AlertDialog mDialog;

    public static Context context;
    //wifi称的连接ip和port(根据不同称设置)
    //启东中医院
    private  final  String  ConnectIp="192.168.43.99";
    private final String ConnnectPort = "8899";
    //wifi方式读取数据
    private Tcp_Client tcp_client = null;
    private final static int CLIENT_STATE_CORRECT_READ = 7;
    public final static int CLIENT_STATE_CORRECT_WRITE = 8;               //正常通信信息
    public final static int CLIENT_STATE_ERROR = 9;                 //发生错误异常信息
    public final static int CLIENT_STATE_IOFO = 10;                  //发送SOCKET信息
    private boolean client_islink = false;
    StringBuffer str = new StringBuffer();
    String weight = "";
    private int rcvLen;
    /*打印功能*/
    private String time;
    private String type;
    private String Weigets;
    private String code;
    private String DName;

    AlertDialog alertDialog;

    printer mPrinter = new printer();

    OkHttpClient moKhttpclient = new OkHttpClient();
    /*da印*/
    private int mKeyTextSize = 26;
    private int mValueTextSize = 20;
    private int mValue2TextSize = 22;
    private int mLineTextSize = 18;
    private int mTitleTextSize = 20;
    /* BarCode Image size  */
    private int mBarcodeSize = 80;
    private int mOffsetX = 210;
    PrintHelper printHelper = null;
    private PrintHelper.PrintType mTitleType = PrintHelper.PrintType.Centering;
    private boolean titleBold = true;

    private String departmentid;
    private static final String Nurse_API = Contants.Nurse_API;
    private static final String UP_DATA_API = Contants.UP_DATA_API;
    public int[] icon = {R.drawable.s, R.drawable.g

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blood_bag_in_bound);
        context = this;
        OutActivity();
        initView();
        ConnectInent();
        resolveIntent(getIntent());
        initReadIC();
        initPrinter();
    }

    private void initReadIC() {
        mDialog = new android.app.AlertDialog.Builder(this).setNeutralButton("Ok", null)
                .create();

        // 获取默认的NFC控制器
        mAdapter = NfcAdapter.getDefaultAdapter(this);

        //拦截系统级的NFC扫描，例如扫描蓝牙
        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        mNdefPushMessage = new NdefMessage(new NdefRecord[] { newTextRecord("",
                Locale.ENGLISH, true) });
    }

    @Override
    protected void onResume() {
        super.onResume();


        if (mAdapter == null) {
            if (!mAdapter.isEnabled()) {
                showWirelessSettingsDialog();
            }

            showMessage("error", " NO NFC");
            showShortToast("设备不支持NFC");


            return;
        }
        if (!mAdapter.isEnabled()) {
            showShortToast("请在系统设置中先启用NFC功能");

            return;
        }

        if (mAdapter != null) {
            //隐式启动
            mAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
            mAdapter.enableForegroundNdefPush(this, mNdefPushMessage);
        }
           registerBroadcast();
    }

    public void registerBroadcast() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(m_Broadcastname);
        registerReceiver(receiver, intentFilter);
    }

    public class MyCodeReceiver extends BroadcastReceiver
    {
        private static final String TAG = "MycodeReceiver";
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(m_Broadcastname)) {
                String str = intent.getStringExtra("BARCODE");
                if (!"".equals(str)) {
                    NurseRequest(str);

                }
            }
        }
    }
    private void showMessage(String title, String message) {
        mDialog.setTitle(title);
        mDialog.setMessage(message);
        mDialog.show();
    }

    private NdefRecord newTextRecord(String text, Locale locale,
                                     boolean encodeInUtf8) {
        byte[] langBytes = locale.getLanguage().getBytes(
                Charset.forName("US-ASCII"));

        Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset
                .forName("UTF-16");
        byte[] textBytes = text.getBytes(utfEncoding);

        int utfBit = encodeInUtf8 ? 0 : (1 << 7);
        char status = (char) (utfBit + langBytes.length);

        byte[] data = new byte[1 + langBytes.length + textBytes.length];
        data[0] = (byte) status;
        System.arraycopy(langBytes, 0, data, 1, langBytes.length);
        System.arraycopy(textBytes, 0, data, 1 + langBytes.length,
                textBytes.length);

        return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT,
                new byte[0], data);
    }

    private void showWirelessSettingsDialog() {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
        builder.setMessage("nfc_disabled");
        builder.setPositiveButton(android.R.string.ok,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent = new Intent(
                                Settings.ACTION_WIRELESS_SETTINGS);
                        startActivity(intent);
                    }
                });
        builder.setNegativeButton(android.R.string.cancel,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                });
        builder.create().show();
        return;
    }



    private void initView() {
        Cweghit=findViewById(R.id.Cweghit);
        weightEdit=findViewById(R.id.weight_edit);
        grid=findViewById(R.id.grid);
        keshi=findViewById(R.id.keshi);
        endShoujiBtn=findViewById(R.id.end_shouji_btn);
        jiaoyanEdit=findViewById(R.id.jiaoyan_edit);
        jiaoyan=findViewById(R.id.jiaoyan);
        chongfuBtn=findViewById(R.id.chongfu_btn);
        endShoujiBtn.setOnClickListener(this);
        chongfuBtn.setOnClickListener(this);
        grid.setAdapter(new BloodBagAdapter(this));
        grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (icon[position]) {
                    //感染
                    case R.drawable.s:
                        final String str1 = "10008";
                        Posrequest(str1);
                        break;
                    //损伤类
                    case R.drawable.g:
                        showShortToast("暂无此类型医废");
//                        final String str = "831-002-01";
//                        Posrequest(str);
                        break;
                    //病理类
//                    case R.drawable.f:
//                        final String str3 = "831-003-01";
//                        Posrequest(str3);
////                        showShortToast("暂无此类型医废");
//                        break;
//                    //化学类
//                    case R.drawable.d:
//                        final String str4 = "831-004-01";
//                        Posrequest(str4);
//
////                        showShortToast("暂无此类型医废");
//                        break;
//                    //药物类
//                    case R.drawable.h:
//                        final String str5 = "831-005-01";
//                        Posrequest(str5);
////                        showShortToast("暂无此类型医废");
//
//                        break;
//                    //输液袋
//                    case R.drawable.j:
//                        showShortToast("暂无此类型医废");
//                        break;

                }
            }
        });

    }

    private void Posrequest(final String string) {
        if (TextUtils.isEmpty(keshi.getText().toString())) {
            showShortToast("科室不能为空");
        } else if (TextUtils.isEmpty(jiaoyanEdit.getText().toString())) {
            showShortToast("护士校验不能为空");
        } else if (TextUtils.isEmpty(weightEdit.getText().toString())) {
            showShortToast("重量不能为空");
        } else {
            showProgressDialog();
            new Thread(new Runnable() {
                @Override

                public void run() {
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            PostRequest(string);

                        }
                    });
                }
            }).start();
        }
    }

    private void PostRequest(String string) {
        RequestBody formBody = new FormBody.Builder()
                .add("id", App.getApp().getToken())
                .add("typeCode", string)
                .add("weight", weightEdit.getText().toString())
                .add("handoverName", jiaoyanEdit.getText().toString())
                .add("departmentId", departmentid)
                .build();
        Request request = new Request.Builder()
                .url(UP_DATA_API)
                .post(formBody)
                .build();
        Log.d("UP_DATA_API", UP_DATA_API + "?id=" + App.getApp().getToken()
                + "&typeCode=" + string
                + "&weight=" + weightEdit.getText().toString()
                + "&handoverName=" + jiaoyanEdit.getText().toString()
                + "&departmentId=" + departmentid);
        Call call = moKhttpclient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                dismissProgressDialog();
                                // 放在UI线程弹Toast
                                showLongToast("请求失败，请确认网络");
                            }
                        });                //此处会发生异常//
                    }
                }).start();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String Poststr = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        PostRespomse(Poststr);
                    }
                });


            }
        });

    }

    private void PostRespomse(String poststr) {
        try {
            JSONObject mJson = new JSONObject(poststr);
            String msg = mJson.getString("message");
            if (msg.equals("20004")) {
                dismissProgressDialog();
                showShortToast("网络异常");
            } else if (msg.equals("20005")) {
                dismissProgressDialog();
                Handler mhandle = new Handler();
                mhandle.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showProgressDialog();
                        PrintMessge();

                    }
                }, 20);
            } else if (msg.equals("20017")) {
                dismissProgressDialog();
                showShortToast("重量小于等于零");
            }else if (msg.equals("20006")){
                dismissProgressDialog();
                showShortToast("医废已上传");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            JSONObject datajson = new JSONObject(poststr);
            JSONObject rubbish = datajson.getJSONObject("rubbish");
            type = rubbish.getString("type");
            time = rubbish.getString("upTime");
            code = rubbish.getString("rubbishCode");
            Weigets = rubbish.getString("weight");
            DName = rubbish.getString("departmentName");


        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
    public void initPrinter() {
        printHelper = new PrintHelper();
        printHelper.Open(this);
    }
    private void PrintMessge() {

                // TODO Auto-generated method stub
        printHelper.PrintStringEx(getString(R.string.hosptelname), mTitleTextSize, false, titleBold,mTitleType);
                String str="~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";
                //mPrinter.PrintString(str, mValueTextSize);
        printHelper.PrintLineInit(mLineTextSize);
        printHelper.PrintLineStringByType(str, mLineTextSize, PrintHelper.PrintType.Centering, false);
        printHelper.PrintLineEnd();
        printHelper.SetGrayLevel((byte)0x03);
        printHelper.PrintLineInit(mKeyTextSize);
        printHelper.PrintLineStringByType("类型:", mKeyTextSize,PrintHelper.PrintType.Left, false);
        printHelper.PrintLineString(type, mKeyTextSize, 90, false);//160
        printHelper.PrintLineString("数量：", mKeyTextSize, 200, false);//160
        printHelper.PrintLineString(Weigets, mKeyTextSize, 260, false);//160
        printHelper.PrintLineEnd();
        printHelper.PrintLineInit(mKeyTextSize);
        printHelper.PrintLineStringByType("收集人：", mKeyTextSize,PrintHelper.PrintType.Left, false);
        printHelper.PrintLineString(App.getApp().getName(), mKeyTextSize, 100, false);//160
        printHelper.PrintLineString("校验人：", mKeyTextSize, 200, false);//160
        printHelper.PrintLineString(jiaoyanEdit.getText().toString(), mKeyTextSize, 280, false);//160
        printHelper.PrintLineEnd();
        printHelper.PrintLineInit(mKeyTextSize);
        printHelper.PrintLineStringByType("科室：", mKeyTextSize,PrintHelper.PrintType.Left, false);
        printHelper.PrintLineString(DName, mKeyTextSize, 90, false);//160
        printHelper.PrintLineEnd();
        printHelper.PrintLineInit(mKeyTextSize);
        printHelper.PrintLineStringByType("时间：", mKeyTextSize, PrintHelper.PrintType.Left, false);
        printHelper.PrintLineString(time, mKeyTextSize, 90, false);//160
        printHelper.PrintLineEnd();
        printHelper.PrintLineInit(mKeyTextSize);
        printHelper.PrintLineStringByType("编码：", mKeyTextSize, PrintHelper.PrintType.Left, false);
        printHelper.PrintLineString(code, mKeyTextSize, 90, false);//160
        printHelper.PrintLineEnd();
                Bitmap bm=null;
                try {
                    bm = BarcodeUtil.encodeAsBitmap(code,
                            BarcodeFormat.CODE_128, 300, 100);
                } catch (WriterException e) {
                    e.printStackTrace();
                }
                if(bm!=null)
                {
                    printHelper.PrintBitmap(bm);
                }
        printHelper.PrintLineInit(40);
        printHelper.PrintLineStringByType("", mKeyTextSize, PrintHelper.PrintType.Right, true);//160
        printHelper.PrintLineEnd();

        printHelper.printBlankLine(40);
                Handler   mhandler=new Handler();
                mhandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                    }
                },2000);




    }
    private void OutActivity() {
        inboundbar=findViewById(R.id.inboundbar);
        inboundbar.setLeftTitleClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void ConnectInent() {
        Intent intent = getIntent();

        String ufhdata = intent.getStringExtra("Ufhdata");
        departmentid = intent.getStringExtra("departmentid");
        Log.d("departmentid", departmentid);
        keshi.setText(ufhdata);

    }

    //初步判断是什么类型NFC卡
    private void resolveIntent(Intent intent) {
        String action = intent.getAction();
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
            Parcelable[] rawMsgs = intent
                    .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage[] msgs;
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }
            } else {
                // Unknown tag type
                byte[] empty = new byte[0];
                byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
                Parcelable tag = intent
                        .getParcelableExtra(NfcAdapter.EXTRA_TAG);
                byte[] payload = dumpTagData(tag).getBytes();
                NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN,
                        empty, id, payload);
                NdefMessage msg = new NdefMessage(new NdefRecord[] { record });
                msgs = new NdefMessage[] { msg };
            }
            // Setup the views

//        showShortToast("");
            buildTagViews(msgs);
        }
    }

    //一般公家卡，扫描的信息
    private String dumpTagData(Parcelable p) {
        StringBuilder sb = new StringBuilder();
        Tag tag = (Tag) p;
        byte[] id = tag.getId();
        sb.append("Tag ID (hex): ").append(getHex(id)).append("\n");
        sb.append("Tag ID (dec): ").append(getDec(id)).append("\n");
        sb.append("ID (reversed): ").append(getReversed(id)).append("\n");

        String prefix = "android.nfc.tech.";
        sb.append("Technologies: ");
        for (String tech : tag.getTechList()) {
            sb.append(tech.substring(prefix.length()));
            sb.append(", ");
        }
        sb.delete(sb.length() - 2, sb.length());
        for (String tech : tag.getTechList()) {
            if (tech.equals(MifareClassic.class.getName())) {
                sb.append('\n');
                MifareClassic mifareTag = MifareClassic.get(tag);
                String type = "Unknown";
                switch (mifareTag.getType()) {
                    case MifareClassic.TYPE_CLASSIC:
                        type = "Classic";
                        break;
                    case MifareClassic.TYPE_PLUS:
                        type = "Plus";
                        break;
                    case MifareClassic.TYPE_PRO:
                        type = "Pro";
                        break;
                }
                sb.append("Mifare Classic type: ");
                sb.append(type);
                sb.append('\n');

                sb.append("Mifare size: ");
                sb.append(mifareTag.getSize() + " bytes");
                sb.append('\n');

                sb.append("Mifare sectors: ");
                sb.append(mifareTag.getSectorCount());
                sb.append('\n');

                sb.append("Mifare blocks: ");
                sb.append(mifareTag.getBlockCount());
            }

            if (tech.equals(MifareUltralight.class.getName())) {
                sb.append('\n');
                MifareUltralight mifareUlTag = MifareUltralight.get(tag);
                String type = "Unknown";
                switch (mifareUlTag.getType()) {
                    case MifareUltralight.TYPE_ULTRALIGHT:
                        type = "Ultralight";
                        break;
                    case MifareUltralight.TYPE_ULTRALIGHT_C:
                        type = "Ultralight C";
                        break;
                }
                sb.append("Mifare Ultralight type: ");
                sb.append(type);
            }
        }

        return sb.toString();
    }

    private String getHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = bytes.length - 1; i >= 0; --i) {
            int b = bytes[i] & 0xff;
            if (b < 0x10)
                sb.append('0');
            sb.append(Integer.toHexString(b));
            if (i > 0) {
                sb.append(" ");
            }
        }
        return sb.toString();
    }

    private long getDec(byte[] bytes) {
        long result = 0;
        long factor = 1;
        for (int i = 0; i < bytes.length; ++i) {
            long value = bytes[i] & 0xffl;
            result += value * factor;
            factor *= 256l;
        }
        return result;
    }

    private long getReversed(byte[] bytes) {
        long result = 0;
        long factor = 1;
        for (int i = bytes.length - 1; i >= 0; --i) {
            long value = bytes[i] & 0xffl;
            result += value * factor;
            factor *= 256l;
        }
        return result;
    }

    //显示NFC扫描的数据
    private void buildTagViews(NdefMessage[] msgs) {
        if (msgs == null || msgs.length == 0) {
            return;
        }
        Date now = new Date();
        List<ParsedNdefRecord> records = NdefMessageParser.parse(msgs[0]);
        final int size = records.size();
        for (int i = 0; i < size; i++) {
            TextView timeView = new TextView(this);
            timeView.setText(TIME_FORMAT.format(now));
            ParsedNdefRecord record = records.get(i);

//            showShortToast(String.valueOf(record.getViewText()));
            String viewText = record.getViewText();
            String[] split = viewText.split("\\n");
            String[] split2 = split[1].split(" ");
            final String string = split2[3];

            if (!TextUtils.isEmpty(string)  &&  string.length()>9){

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {

                            Handler handler = new Handler(Looper.getMainLooper());
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    showProgressDialog();
                                    NurseRequest(string);
                                }
                            });
                        } catch (InputMismatchException e) {
                            e.printStackTrace();
                        }

                    }
                }).start();

            }else if(!TextUtils.isEmpty(string)  &&  string.length()<=9){
                final   String  s="0"+string;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {

                            Handler handler = new Handler(Looper.getMainLooper());
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    showProgressDialog();
                                    NurseRequest(s);
                                }
                            });
                        } catch (InputMismatchException e) {
                            e.printStackTrace();
                        }

                    }
                }).start();

            }else{
                showShortToast("读卡失败，请重新读");
            }

//            jiaoyanEdit.setText(string);

            Log.d("record", String.valueOf(string));
        }
    }

    //获取系统隐式启动的
    @Override
    public void onNewIntent(Intent intent) {
        setIntent(intent);
        resolveIntent(intent);
    }

    private void NurseRequest(String epcStr) {
        OkHttpClient moKhttp = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("id", App.getApp().getToken())
                .add("cardCode", epcStr)
                .build();
        Request request = new Request.Builder()
                .url(Nurse_API)
                .post(formBody)
                .build();
        Log.d("Nurse_API", Nurse_API + "?id=" + App.getApp().getToken() + "&cardCode=" + epcStr);
        Call call = moKhttp.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                dismissProgressDialog();
                                // 放在UI线程弹Toast
                                showLongToast("请求失败，请确认网络");
                            }
                        });                //此处会发生异常//
                    }
                }).start();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String nursestr = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        NurseResponse(nursestr);
                    }
                });
            }
        });


    }

    private void NurseResponse(String nursestr) {
        try {
            JSONObject NurseJson = new JSONObject(nursestr);
            String NurseMsg = NurseJson.getString("message");
            if (NurseMsg.equals("20005")) {
                dismissProgressDialog();

            } else if (NurseMsg.equals("20008")) {
                dismissProgressDialog();
                showShortToast("查无此卡");
            } else if (NurseMsg.equals("20009")) {
                dismissProgressDialog();
                showShortToast("类型不符");
            } else if (NurseMsg.equals("20015")) {
                dismissProgressDialog();
                showShortToast("产生点不符");
            } else if (NurseMsg.equals("20019")) {
                dismissProgressDialog();
                showShortToast("卡片未分配");
            } else if (NurseMsg.equals("20020")) {
                dismissProgressDialog();
                showShortToast("上步操作未完成");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            JSONObject NusrseData = new JSONObject(nursestr);
            String handoverName = NusrseData.getString("handoverName");
            jiaoyanEdit.setText(handoverName);
            if (!TextUtils.isEmpty(jiaoyanEdit.getText().toString())) {

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void ConnectWIFI() {
        if (tcp_client == null) {
            tcp_client = new Tcp_Client(cli_handler);
            try {
                InetAddress ipAddress = InetAddress.getByName
                        (ConnectIp);
                int port = Integer.valueOf(ConnnectPort);//获取端口号
                tcp_client.setInetAddress(ipAddress);
                tcp_client.setPort(port);

            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            tcp_client.start();
        }
    }

    //客户端通信模式下
    @SuppressLint("HandlerLeak")
    private Handler cli_handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CLIENT_STATE_ERROR:
                    initAlert();
                    if (tcp_client != null) {
                        tcp_client.close();
                        tcp_client = null;
                    }
                    client_islink = false;
                    break;
                case CLIENT_STATE_IOFO:
                    client_islink = true;

                    break;
                //接收数据
                case CLIENT_STATE_CORRECT_READ:
                    Handler_receive(msg);
                    break;

            }
        }
    };

    private void Handler_receive(Message msg) {

        Log.d("ddieokdk", msg.obj.toString());

        weightEdit.setText(String.valueOf(msgMatch(msg.obj.toString())));
    }

    public  static  String msgMatch(String str){
        Pattern pattern = Pattern.compile("-  \\d{1,2}.\\d{0,3}|\\d{1,2}.\\d{0,3}");
        Matcher matcher = pattern.matcher(str);
        boolean find = matcher.find();
        String group = "0";
        if (find) {
            group = matcher.group();
        }
        return group;
    }

    private void initAlert() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(R.mipmap.ic_launcher_round);
        builder.setTitle("提示");
        builder.setMessage("请确认秤打开或者再有电状态");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
//                ConnectWIFI();
            }
        });
        builder.setNegativeButton("取消", null);
        alertDialog = builder.create();
        if (!BloodBagInBoundActivity.this.isFinishing()&& !alertDialog.isShowing()) {
            alertDialog.show();
        }

    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.end_shouji_btn:
                Intent intent = new Intent(BloodBagInBoundActivity.this, KeshiActivity.class);
                intent.putExtra("departmentid",departmentid);
                startActivity(intent);
                finish();
                break;
            case R.id.chongfu_btn:
                if (departmentid.toString()==null){
                    showShortToast("请先选择类型打印");
                }else{
                    Handler mhandle = new Handler();
                    mhandle.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            showProgressDialog();
                            PrintMessge();
                        }
                    }, 20);
                }

                break;


        }
    }

    @Override
    protected void onPause() {

        super.onPause();
        if (alertDialog != null && alertDialog.isShowing()) {
            alertDialog.dismiss();
        }




    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (tcp_client != null) {
            tcp_client.close();
            tcp_client = null;
        }


    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

}
